﻿jQuery(function($) {
	var pageHistory = [];
	var isAnimating = false;
	
	$(".page").hide();
	pageHistory.push($("#home").show());
	
	$("a[href^=#]").click(function(event) {
		var target = $($(this).attr("href"));
		if (target.length) {
			event.preventDefault();
			pageNavigate(target);
		}
	});
	
	$("a.back").click(function(event) {
		event.preventDefault();
		pageBack();
	});
	
	var imageBox = $("<div class='image-box'><img/></div>").appendTo(document.body);
	$(".current-photo a").click(function(event) {
		event.preventDefault();
		
		var el = $(".current-photo");
		var page = $("#detail");
		var offset = el.offset();
		offset.left -= $("#detail").offset().left;
		offset.width = el.width();
		offset.height = el.height();
		imageBox
			.find("img").attr("src", $(this).attr("href")).end()
			.css({ left: offset.left, top: offset.top, width: offset.width, height: offset.height, opacity: 0 })
			.show().animate({
				left: 0, top: 0, width: page.width(), height: page.height(), opacity: 1
			}, {})
			.unbind("click").click(function(event) {
				$(this).animate({
					left: offset.left, top: offset.top, width: offset.width, height: offset.height, opacity: 0
				}, {
					complete: function() {
						$(this).hide();
					}
				});
			});
	});
	
	function pageNavigate(page)
	{
		if (isAnimating) {
			return false;
		}
		page = $(page);
		
		var current = pageHistory[pageHistory.length - 1];
		var width = current.width();
		isAnimating = true;
		pageHistory.push(page);
		
		current.animate({ left: -width }, {
			complete: function() {
				isAnimating = false;
			}
		});
		page.show().css("left", width).animate({
			left: 0
		}, {});
	}
	
	function pageBack()
	{
		if (isAnimating || pageHistory.length <= 1) {
			return false;
		}
		
		var current = pageHistory[pageHistory.length - 1];
		var prev = pageHistory[pageHistory.length - 2];
		var width = current.width();
		isAnimating = true;
		pageHistory.pop();

		current.animate({ left: width }, {
			complete: function() {
				isAnimating = false;
			}
		});
		prev.css("left", -width).animate({ left: 0 }, {});
	}
});

window.onload = function() {
	if (/\biPhone\b/.test(navigator.userAgent)) {
		setTimeout(function() {
			if (window.pageYOffset === 0) {
				window.scrollTo(0, 1);
			}
		}, 100);
	};
};
